//
//  FontSetViewController.m
//  ebook
//
//  Created by ChenNan on 16/6/22.
//  Copyright © 2016年 Moton. All rights reserved.
//

#import "FontSetViewController.h"
#import "ReaderGlobalModel.h"
#import "FontModel.h"
#import "FontsDownloadManager.h"
#import "EbookNetRequest.h"
#import "MBProgressHUD.h"
#import "AppConfigManager.h"

@interface FontSetViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic,   copy) NSString *fullname;
@property (nonatomic, strong) NSIndexPath *lastIndexPath;
@property (nonatomic, strong) MBProgressHUD *HUD;

@end

@implementation FontSetViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"字体设置";
    [self createBackBtn];
    
    NSArray *array = [ReaderGlobalModel shareModel].fontsDataArray;
    if (!array) {
        [self showHUD];
        __block FontSetViewController *weakSelf = self;
        [self requestFontsDataComplete:^(NSDictionary *dict) {
            __strong __typeof(self) strongSelf = weakSelf;
            [strongSelf hideHUD];
            [strongSelf initWithDic:dict];
            [strongSelf.view addSubview:strongSelf.tableView];
        }];
    } else {
        _dataArray = [NSMutableArray arrayWithArray:array];
        _fullname = [ReaderGlobalModel shareModel].readerConfig.fontFullname;
        _lastIndexPath = [NSIndexPath indexPathForRow:[self getLastRow:_dataArray] inSection:0];
        
        [self.view addSubview:self.tableView];
    }
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateDownloadFontsProgress:) name:kDownloadFontsNotification object:nil];
}

- (void)requestFontsDataComplete:(void(^)(NSDictionary *dict))complete {
    
    [EbookNetRequest downloadFontListSuccess:^(int stateCode, NSString *successMsg, NSDictionary *dict) {
        complete(dict);
    } failed:^(int stateCode, NSString *failMsg) {
        
    }];
}

- (UITableView *)tableView {
    
    if (!_tableView) {
        CGRect frame = [UIScreen mainScreen].bounds;
        frame.size.height -= SafeAreaTopHeight;
        if(MTScreenH==480)frame.size.height -= 49;//4s屏幕尺寸问题，视图大小需单独计算
        _tableView = [[UITableView alloc] initWithFrame:frame style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorInset = UIEdgeInsetsMake(0, 15, 0, 0);
        _tableView.separatorColor = MTColor(226, 228, 230, 1);
        _tableView.scrollEnabled = YES;
    }
    return _tableView;
}

- (void)initWithDic:(NSDictionary *)dic {
    
    //服务器字体列表
    NSMutableArray *array = [[NSMutableArray alloc] initWithArray:dic[@"list"]];
    
    //本地字体列表
    NSMutableArray *arr = [NSMutableArray arrayWithArray:[[AppConfigManager shareManager] FontsData]];
    
    for (NSDictionary *dic in array) {
        for (int i = 0; i < arr.count; i++) {
            NSDictionary *d = arr[i];
            if ([dic[@"postscript"] isEqualToString:d[@"postscript"]]) {
                [arr removeObject:d];
            }
        }
    }
    
    for (NSDictionary *d in arr) {
        
        [array insertObject:@{@"postscript":d[@"postscript"],@"fullname":d[@"fullname"], @"fontname":d[@"fontname"],@"downurl":@"", @"size":@"",@"isDownloading":@NO,@"isDownloaded":@YES} atIndex:0];
    }
    
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:kFontsData];
    [[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:array] forKey:kFontsData];
    [[NSUserDefaults standardUserDefaults] synchronize];

    _fullname = [ReaderGlobalModel shareModel].readerConfig.fontFullname;
    _lastIndexPath = [NSIndexPath indexPathForRow:[self getLastRow:array] inSection:0];
    
    _dataArray = [[NSMutableArray alloc] initWithArray:[self setFontData:array]];
    [ReaderGlobalModel shareModel].fontsDataArray = _dataArray;
}

- (void)showHUD{
    
    if (!_HUD) {
        _HUD = [[MBProgressHUD alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
        _HUD.center = self.view.center;
    }
    [self.view addSubview:_HUD];
    [self.view bringSubviewToFront:_HUD];
    [_HUD show:YES];
}

- (void)hideHUD{
    
    [_HUD removeFromSuperview];
    _HUD = nil;
}

//获取上次保存的row
- (NSInteger)getLastRow:(NSArray *)array {
    
    __block NSInteger index = 0;
    if ([array[0] isKindOfClass:[FontModel class]]) {
        [array enumerateObjectsUsingBlock:^(FontModel *model, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([model.fullname isEqualToString:_fullname]) {
                index = idx;
                *stop = YES;
            }
        }];
    } else {
        [array enumerateObjectsUsingBlock:^(NSDictionary *dic, NSUInteger idx, BOOL * stop) {
            if ([dic[@"fullname"] isEqualToString:_fullname]) {
                index = idx;
                *stop = YES;
            }
        }];
    }
    return index;
}

- (NSMutableArray *)setFontData:(NSArray *)array{
    
    NSString *path = [NSString stringWithFormat:@"%@/%@", PATH_OF_DOCUMENT, @"Fonts"];
    NSArray *localArray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:nil];
    NSMutableArray *fontsArray = [[NSMutableArray alloc] init];
    [array enumerateObjectsUsingBlock:^(NSDictionary *dic, NSUInteger idx, BOOL *stop) {
        FontModel *model = [[FontModel alloc] initWithDictionary:dic];
        [fontsArray addObject:model];
    }];
    for (int i = 0; i < localArray.count; i++) {
        NSString *filename = localArray[i];
        for (FontModel *model in fontsArray) {
            if ([filename isEqualToString:model.postscript]) {
                model.isDownloaded = YES;
            }
        }
    }
    return fontsArray;
}

- (void)updateDownloadFontsProgress:(NSNotification *)noti {
    
    NSDictionary *dic = noti.object;
    FontModel *model = dic[@"model"];
    float progress = [dic[@"progress"] floatValue];
    model.percent = [NSString stringWithFormat:@"正在下载 %.1f%@", progress*100, @"%"];
    if (progress < 1.0) {
        model.isDownloading = YES;
        model.isDownloaded = NO;
    } else {
        model.isDownloading = NO;
        model.isDownloaded = YES;
        __block UITableView *weakTableView = _tableView;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [weakTableView reloadData];
        });
    }
    
    for (int i = 0; i < _dataArray.count; i++) {
        FontModel *m1 = _dataArray[i];
        if ([m1.postscript isEqualToString:model.postscript]) {
            [_dataArray replaceObjectAtIndex:i withObject:model];
        }
    }
    [_tableView reloadData];
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    
    FontModel *model = _dataArray[_lastIndexPath.row];
    [ReaderGlobalModel shareModel].readerConfig.fontName = model.fontname;
    [ReaderGlobalModel shareModel].readerConfig.fontFullname = model.fullname;
    [ReaderGlobalModel shareModel].readerConfig.postScript = model.postscript;
    [[NSNotificationCenter defaultCenter] postNotificationName:KApplyFontNotification object:nil];
}

#pragma mark - navi back btn
- (void)createBackBtn
{
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back_arrow"] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    backItem.tintColor = MTConfigColor(@"MTNavigationBar_leftItem_Color");
    self.navigationItem.leftBarButtonItem = backItem;
}

- (void)back
{
    [self dismissViewControllerAnimated:YES completion:nil];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - table

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 50;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView *view = [[UIView alloc] init];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(15, 20, MTScreenW-20, 25)];
    label.font = [UIFont systemFontOfSize:12.0];
    label.textColor = [UIColor darkGrayColor];
    label.text = @"字体选择";
    [view addSubview:label];
    return view;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return _dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *identifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
    }
    FontModel *model = _dataArray[indexPath.row];
    
    cell.textLabel.textColor = [UIColor darkTextColor];
    cell.detailTextLabel.textColor = [UIColor lightGrayColor];
    cell.detailTextLabel.font = [UIFont systemFontOfSize:12.0];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.imageView.image = [UIImage imageNamed:@"fontpicker_nl"];
    cell.textLabel.text = model.fullname;
    if ([model.fullname isEqualToString:_fullname]) {
        cell.imageView.image = [UIImage imageNamed:@"fontpicker_sl"];
    }
    
    UIButton *downloadBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    downloadBtn.frame = CGRectMake(MTScreenW-80, 0, 70, cell.height);
    [downloadBtn setTitle:[NSString stringWithFormat:@"%.fM",model.size/1024/1024] forState:UIControlStateNormal];
    downloadBtn.titleLabel.font = [UIFont systemFontOfSize:12.0];
    [downloadBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    downloadBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -50, 0, 0);
    [downloadBtn setImage:[UIImage imageNamed:@"fontdownload"] forState:UIControlStateNormal];
    downloadBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 40, 0, 0);
    [downloadBtn addTarget:self action:@selector(downloadFont:) forControlEvents:UIControlEventTouchUpInside];
    downloadBtn.tag = indexPath.row;
    
    //判断字体是否已下载
    if (model.isDownloaded) {
        for (UIView  *subView in cell.subviews) {
            if ([subView isKindOfClass:[UIButton class]]) {
                [subView removeFromSuperview];
            }
        }
        cell.detailTextLabel.text = @"已下载";
    }else{
        if (0 == indexPath.row) {
            cell.detailTextLabel.text = nil;
        }else{
            BOOL iscontainbtn = NO;
            for (UIView *subView in cell.subviews) {
                if ([subView isKindOfClass:[UIButton class]]) {
                    iscontainbtn = YES;
                }
            }
            if (!iscontainbtn) {
                [cell addSubview:downloadBtn];
            }
            
            cell.imageView.image = [UIImage imageNamed:@"fontpicker_no"];
        }
    }
    
    for (FontModel *m1 in [[FontsDownloadManager shareInstance] currentDownloadQueue]) {
        if ([m1.postscript isEqualToString:model.postscript]) {
            for (UIView *subView in cell.subviews) {
                if ([subView isKindOfClass:[UIButton class]]) {
                    [subView removeFromSuperview];
                }
            }
        }
        if (m1.percent && [cell.textLabel.text isEqualToString:m1.fullname]) {
            cell.detailTextLabel.text = m1.percent;
        }
        if (!m1.percent && [cell.textLabel.text isEqualToString:m1.fullname]) {
            cell.detailTextLabel.text = @"等待下载中...";
        }
    }
    
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    FontModel *model = _dataArray[indexPath.row];
    if ((!model.isDownloaded && !model.isDownloading) || model.isDownloading) return;
    
    _fullname = model.fullname;
    
    if (indexPath.row != _lastIndexPath.row)
    {
        UITableViewCell *newCell = [tableView cellForRowAtIndexPath:indexPath];
        newCell.imageView.image = [UIImage imageNamed:@"fontpicker_sl"];
        UITableViewCell *oldCell = [tableView cellForRowAtIndexPath: _lastIndexPath];
        oldCell.imageView.image = [UIImage imageNamed:@"fontpicker_nl"];
        _lastIndexPath = indexPath;
    }
}

- (void)downloadFont:(UIButton *)btn {
    
    UITableViewCell *cell = (UITableViewCell *)[btn superview];
    NSIndexPath * indexPath = [self.tableView indexPathForCell:cell];
    FontModel *model = _dataArray[indexPath.row];
    
    [[FontsDownloadManager shareInstance] addDownloadFont:model];
}

- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
